package practice;

/**
 * 案例：3个窗口抢100张票【同步方法】
 */
public class Practice2 {

    private static int ticket = 0;

    public static void main(String[] args) {
        MyThread myThread = new MyThread();

        Thread t1 = new Thread(myThread, "窗口1");
        Thread t2 = new Thread(myThread, "窗口2");
        Thread t3 = new Thread(myThread, "窗口3");

        t1.start();
        t2.start();
        t3.start();
    }


    private static class MyThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                if (method()) break;
            }
        }

        private synchronized Boolean method() {
            if (ticket < 100) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ticket++;
                System.out.println(Thread.currentThread().getName() + "正在抢票：" + ticket);
                return false;
            } else {
                return true;
            }
        }

    }


}
